#define _XOPEN_SOURCE 500
 
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
 
#define STEP 1024

char *makemsg(char f[])
{
  char		       	*msg;
  size_t					s		;
  s = strlen(f);
  msg = malloc(s + 7);
  strncpy(msg,"mycat: ",7);
  strncat(msg,f,s);
  return msg;
}

void mycat(char f[])
{
  int 			fd;
  char			buf[STEP];
  int				r;
  
  if(f[0] == '-')
    fd = STDIN_FILENO;
  else
  {
    if((fd = open(f,O_RDONLY)) == -1)
    {
    	perror (makemsg(f));
			exit (2);
    }
	}
	
  while((r = read(fd, buf, STEP)))
  {
  	if(r == -1)
  	{
  		if ( errno == EINTR || errno == EAGAIN )
		    continue;
			perror (makemsg(f));
		  exit (3);
		}
		write(STDOUT_FILENO,buf,r);
  }
  close(fd);
}
 
int main(int argc, char *argv[])
{
    if(argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
  {
    write(STDOUT_FILENO,"Usage : ",8);
   	write(STDOUT_FILENO, argv[0],strlen(argv[0]));
   	write(STDOUT_FILENO," file1 file2 ...",16);
    return (0);
  }
  
  if(argc < 2)
  {
    write(STDERR_FILENO,"Missing parameters\nUsage : ",28);
    write(STDERR_FILENO, argv[0],strlen(argv[0]));
    write(STDERR_FILENO," file1 file2 ...",16);
    
    exit(1);
  }  
  
  for (int i=1; i<argc; ++i)
    mycat(argv[i]);
  return (0);
}
